package com.zzg.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzg.srb.common.exception.Assert;
import com.zzg.srb.common.result.ResponseEnum;
import com.zzg.srb.core.entity.pojo.*;
import com.zzg.srb.core.entity.vo.BorrowInfoApprovalVo;
import com.zzg.srb.core.entity.vo.BorrowerDetailVo;
import com.zzg.srb.core.enums.BorrowInfoStatusEnum;
import com.zzg.srb.core.enums.BorrowerStatusEnum;
import com.zzg.srb.core.enums.DictEnum;
import com.zzg.srb.core.mapper.BorrowInfoMapper;
import com.zzg.srb.core.mapper.BorrowerMapper;
import com.zzg.srb.core.mapper.IntegralGradeMapper;
import com.zzg.srb.core.mapper.UserInfoMapper;
import com.zzg.srb.core.service.BorrowInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzg.srb.core.service.BorrowerService;
import com.zzg.srb.core.service.DictService;
import com.zzg.srb.core.service.LendService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author zhengzg
 * @since 2022-05-27
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private IntegralGradeMapper integralGradeMapper;

    @Resource
    private DictService dictService;

    @Resource
    private BorrowerMapper borrowerMapper;

    @Resource
    private BorrowerService borrowerService;

    @Resource
    private LendService lendService;

    @Override
    public BigDecimal getBorrowAmount(Long userId) {

        //获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        Integer integral = userInfo.getIntegral();

        //根据积分查询借款额度
        LambdaQueryWrapper<IntegralGrade> integralGradeQueryWrapper = new LambdaQueryWrapper<>();
        integralGradeQueryWrapper
                .le(IntegralGrade::getIntegralStart,integral)
                .ge(IntegralGrade::getIntegralEnd,integral);

        IntegralGrade integralGrade = integralGradeMapper.selectOne(integralGradeQueryWrapper);
        if (Objects.isNull(integralGrade)){
            return BigDecimal.ZERO;
        }

        return integralGrade.getBorrowAmount();
    }

    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {

        //获取userInfo的用户数据
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //判断用户信息是否审批通过
        Assert.isTrue(
                userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_AMOUNT_ERROR);

        //判断借款额度是否足够
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        Assert.isTrue(
                borrowInfo.getAmount().doubleValue() <= borrowAmount.doubleValue(),
                ResponseEnum.USER_AMOUNT_LESS_ERROR);

        //存储数据
        borrowInfo.setUserId(userId);

        //百分比转成小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal("100")));
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        baseMapper.insert(borrowInfo);
    }

    @Override
    public Integer getStatusByUserId(Long userId) {
        LambdaQueryWrapper<BorrowInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .select(BorrowInfo::getStatus)
                .eq(BorrowInfo::getUserId,userId);

        List<Object> objects = baseMapper.selectObjs(queryWrapper);

        if (CollectionUtils.isEmpty(objects)){
            //借款人尚未提交信息
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        return (Integer) objects.get(0);
    }

    @Override
    public List<BorrowInfo> selectList() {
        List<BorrowInfo> borrowInfos = baseMapper.selectBorrowInfoList();
        borrowInfos.forEach(this::packageBorrowInfo);
        return borrowInfos;
    }

    @Override
    public Map<String, Object> getBorrowInfoDetail(Long id) {

        //查询借款对象
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        //组装数据
        BorrowInfo packageBorrowInfo = packageBorrowInfo(borrowInfo);

        //根据User_id获取借款人对象
        LambdaQueryWrapper<Borrower> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Borrower::getUserId,packageBorrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(queryWrapper);
        //组装借款人对象
        BorrowerDetailVo borrowerDetailVo = borrowerService.getBorrowerDetailVoById(borrower.getId());

        //组装数据
        HashMap<String, Object> result = new HashMap<>();
        result.put("borrowInfo",borrowInfo);
        result.put("borrower",borrowerDetailVo);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowInfoApprovalVo borrowInfoApprovalVo) {

        //修改借款信息状态
        Long borrowInfoId = borrowInfoApprovalVo.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        borrowInfo.setStatus(borrowInfoApprovalVo.getStatus());
        baseMapper.updateById(borrowInfo);

        //审核通过规则建标
        if(borrowInfoApprovalVo.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()){
            //创建标的
            lendService.createLeand(borrowInfoApprovalVo, borrowInfo);
        }
    }

    /**
     * 组装借款对象信息
     * @param borrowInfo
     * @return
     */
    private BorrowInfo packageBorrowInfo(BorrowInfo borrowInfo){
        //组装数据
        String returnMethod = dictService.getNameByParentDictCodeAndValue(DictEnum.RETURN_METHOD.getDictCode(), borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue(DictEnum.MONEY_USER.getDictCode(), borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put(DictEnum.RETURN_METHOD.getDictCode(),returnMethod);
        borrowInfo.getParam().put(DictEnum.MONEY_USER.getDictCode(),moneyUse);
        borrowInfo.getParam().put("status",status);
        return borrowInfo;
    }
}
